/*
 * @Date: 2025-06-13 11:12:23
 * @Auth: 463997479@qq.com
 * @LastEditors: 463997479@qq.com
 * @LastEditTime: 2025-09-30 16:54:28
 * @FilePath: \corpus\src\pages\corpusFile\index.tsx
 */
import type { ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable, TableDropdown } from '@ant-design/pro-components';
import hooks from './hooks';

import { getKnowledFile } from '@/services/ant-design-pro/corpus/index';
import {
  CheckCircleFilled,
  ClockCircleFilled,
  CloseCircleFilled,
  MinusCircleFilled,
} from '@ant-design/icons';
import { useModel } from '@umijs/max';
import { Button, Popconfirm } from 'antd';
import React, { useEffect, useMemo } from 'react';
import EditUpload from './EditUpload';
import SplitCorpus from './SplitCorpus';
import styles from './index.less';
const typeEnum: Record<string, string> = {
  '0': '失败',
  '1': '解析向量化中',
  '2': '解析向量化成功',
  '3': '待解析向量化',
};
const CorpusFile: React.FC = () => {
  const {
    actionRef,
    knowledgeId,
    getAnalysisFile,
    setEditFile,
    getKnowledgeJson,
    data,
    deleteFile,
    getData,
    type,
  } = hooks.useContainer();

  const { getRole } = useModel('useUser', (model) => {
    return {
      getRole: model.getRole,
    };
  });
  useEffect(() => {
    getData.run({});
  }, []);

  const hasUploadPermission = useMemo(() => {
    return getRole(`ptknowledge:upload`);
  }, [type]);

  const columns: ProColumns<any>[] = [
    {
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
      title: '序号',
    },
    {
      title: 'id',
      dataIndex: 'id',
      hideInForm: false,
      ellipsis: true,
      search: false,
      width: 100,
    },

    {
      title: '文档名称',
      dataIndex: 'fileName',
      ellipsis: true,
    },
    {
      title: '文档内容',
      dataIndex: 'content',
      ellipsis: true,
      hideInSearch: true,
      render: (_, record) => {
        return <span title={record.content}>{record.content}</span>;
      },
    },

    {
      title: '是否文本',
      dataIndex: 'contentQuery',
      initialValue: '0',
      hideInTable: true,
      width: 100,
      valueType: 'radio',
      valueEnum: {
        1: { text: '是', status: 'yes' },
        0: { text: '否', status: 'no' },
      },
    },

    // {
    //   title: '文档地址',
    //   dataIndex: 'ossUrl',
    //   ellipsis: true,
    // },
    // {
    //   title: '文档类型',
    //   dataIndex: 'fileSuffix',
    //   ellipsis: true,
    // },
    {
      title: '上传时间',
      dataIndex: 'createTime',
      ellipsis: true,
      search: false,
    },
    {
      title: '上传时间',
      dataIndex: 'time',
      ellipsis: true,
      hideInTable: true,

      valueType: 'dateRange',
      search: {
        transform: (value) => {
          return {
            startTime: value[0],
            endTime: value[1],
          };
        },
      },
    },

    {
      title: '解析状态',
      dataIndex: 'analysisStatus',
      ellipsis: true,
      valueType: 'select',
      valueEnum: {
        '0': {
          text: '失败',
          status: 'Error',
        },
        '1': {
          text: '解析向量化中',
          status: 'Pending',
        },
        '2': {
          text: ' 解析向量化成功',
          status: 'Success',
        },
        '3': {
          text: '待解析向量化',
          status: 'Pending',
        },
      },
      render: (_, record: any) => [
        <span key={1}>
          {record?.analysisStatus === 1 ? (
            <ClockCircleFilled style={{ color: 'green' }} />
          ) : record?.analysisStatus === 2 ? (
            <CheckCircleFilled style={{ color: 'green' }} />
          ) : record?.analysisStatus === 3 ? (
            <MinusCircleFilled style={{ color: '#1890ff' }} />
          ) : (
            <CloseCircleFilled style={{ color: 'red' }} />
          )}
          <span style={{ marginLeft: '5.0px' }}>{typeEnum[record?.analysisStatus + '']}</span>
        </span>,
      ],
    },

    {
      title: '操作',
      width: 162,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record: any) => [
        <Popconfirm
          key={1}
          title="知识库解析"
          description={`确认解析当前知识库？`}
          onConfirm={() => {
            getAnalysisFile.run({ fileId: record?.id });
          }}
          onCancel={() => {}}
          okText="确认"
          cancelText="取消"
        >
          {record?.analysisStatus === 0 && <a>知识库解析</a>}
        </Popconfirm>,
        // <Popconfirm
        //   key={1}
        //   title="知识向量化"
        //   description={`知识向量化？`}
        //   onConfirm={() => {
        //     getAnalysisFile.run({ fileId: record?.id });
        //   }}
        //   onCancel={() => {}}
        //   okText="确认"
        //   cancelText="取消"
        // >
        //   {record?.analysisStatus === 0 && <a>知识向量化</a>}
        // </Popconfirm>,

        <Popconfirm
          key={2}
          title="知识库"
          description={`确认删除？`}
          onConfirm={() => {
            deleteFile.run(record?.id);
          }}
          onCancel={() => {}}
          okText="确认"
          cancelText="取消"
        >
          {hasUploadPermission && <a>删除</a>}
        </Popconfirm>,
        <TableDropdown
          key="actionGroup"
          onSelect={(val) => {
            switch (val) {
              case 'source':
                window.open(
                  `${window.location.origin}/corpus/knowledgeFile/downloadFile?fileId=${record?.id}`,
                );
                break;
              case 'text':
                window.open(
                  `${window.location.origin}/corpus/knowledgeFile/downloadText?fileId=${record?.id}`,
                );
                break;

              case 'json':
                getKnowledgeJson.run({ fileId: record?.id });
                break;
            }
          }}
          menus={[
            { key: 'source', name: '下载源文件' },
            { key: 'text', name: '下载文本' },
            { key: 'json', name: '拆条' },
          ]}
        >
          更多
        </TableDropdown>,
      ],
    },
  ];
  const getAction = () => {
    return (
      <>
        {hasUploadPermission && (
          <Button
            key="button"
            onClick={() => {
              setEditFile(true);
            }}
            type="primary"
          >
            新建{}
          </Button>
        )}
      </>
    );
  };
  return (
    <PageContainer className={styles.detailWrap}>
      <ProTable<API.RuleListItem, API.PageParams>
        toolBarRender={() => [getAction()]}
        actionRef={actionRef}
        rowKey="key"
        request={async (
          // 第一个参数 params 查询表单和 params 参数的结合
          // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
          params: any,
        ) => {
          // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
          // 如果需要转化参数可以在这里进行修改
          if (params.time) {
            params.createStartTime = params.time[0];
            params.createEndTime = params.time[1];
          }
          if (params.contentQuery === '0') {
            params.contentQuery = false;
          } else {
            params.contentQuery = true;
          }
          const msg = await getKnowledFile({
            ...params,
            knowledgeId: knowledgeId,
          });
          return {
            data: msg.data,
            // success 请返回 true，
            // 不然 table 会停止解析数据，即使有数据
            success: true,
            // 不传会使用 data 的长度，如果是分页一定要传
            total: msg.total,
          };
        }}
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          showSizeChanger: true,
          defaultPageSize: 10,
        }}
        columns={columns}
      />
      <EditUpload />
      <SplitCorpus />
    </PageContainer>
  );
};

export default () => {
  return (
    <hooks.Provider>
      <CorpusFile />
    </hooks.Provider>
  );
};
